# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from flask import Blueprint, current_app, request, render_template, session, url_for, send_file, abort, make_response, Response

import os

try:
    import json
except ImportError:
    import simplejson as json

from ..loginwrapper import login_required, public_network_protection

from ..extra_config import STORE_IMAGE_FOLDER

from ..util import md5, formatDT, getSplitExt, getImageMime, fromTimeStamp

_file = Blueprint(
    'file',
    __name__,
    static_folder='../static',
    template_folder='../templates'
)

MODULE_NAME = 'file'
TEMPLATE_FOLDER = 'file'

def log(msg, level='debug'):
    getattr(current_app.loger, level)(msg, MODULE_NAME)

def getExcept():
    return current_app.loger.getExcept()

def logExcept():
    ex_msg = getExcept()
    log(ex_msg, 'error')

def template_path(template_file):
    return '{0}/{1}'.format(
        TEMPLATE_FOLDER,
        template_file
    )

@_file.route(r'/image_upload/', methods=['POST'])
@public_network_protection
@login_required
def image_upload():
    image_key = 'image'
    ret = {}
    if image_key in request.files:
        _image = request.files[image_key]
        _fb, _fe = getSplitExt(_image.filename)
        _fb = md5(formatDT())
        _fn = '{0}.{1}'.format(_fb, _fe)
        _save_path = os.path.join(STORE_IMAGE_FOLDER, _fn)
        _image.save(_save_path)
        ret['msg'] = '上传成功'
        ret['success'] = True
        ret['file_path'] = url_for('.image', path=_fn)
    else:
        ret['msg'] = '未找到上传的图片'
        ret['success'] = False
    return json.dumps(ret)

@_file.route(r'/image/<path>', methods=['GET', 'POST'])
@public_network_protection
def image(path=None):
    if not path is None:
        file_abs_path = os.path.join(STORE_IMAGE_FOLDER, path)
        if os.path.exists(file_abs_path):
            header_modify = request.headers.get('If-Modified-Since')
            modify_time = os.path.getmtime(file_abs_path)
            if bool(modify_time) and isinstance(modify_time, float):
                img_modify = fromTimeStamp(modify_time).ctime()
            else:
                img_modify = None
            if bool(header_modify) and header_modify == img_modify:
                return Response(status=304)
            mime = getImageMime(file_abs_path)
            resp = make_response(send_file(file_abs_path, mimetype='image/{0}'.format(mime)))
            if not img_modify is None:
                resp.headers['Last-Modified'] = img_modify
            return resp
    return abort(404)